#include <QtGui>

#include "TimerSlider.h"
#include "Debug.h"

void sec_to_string( int sec, QString &output );

/**
 * @brief The constructor of TimerSlider
 */
TimerSlider::TimerSlider( QWidget *parent )
	: QWidget( parent )
{
	QVBoxLayout *layout = new QVBoxLayout;

	slider = new QSlider(Qt::Horizontal);
	slider->setRange( 0, 0 );

	timer = new QLCDNumber;
	timer->setSegmentStyle(QLCDNumber::Flat);
	timer->setNumDigits(8);

	setTimer(0);

	/* Connect the valueChanged() signal from "slider" to the corresponding
	 * slot:setTimer(). */
	connect(slider, SIGNAL(valueChanged(int)),
		this, SLOT(setTimer(int)));
	/* Reconnect the signals of QSlider to the signals of TimerSlider */
	connect(slider, SIGNAL(sliderPressed()),
		this, SIGNAL(sliderPressed()));
	connect(slider, SIGNAL(sliderReleased()),
		this, SIGNAL(sliderReleased()));

	layout->addWidget(timer);
	layout->addWidget(slider);
	setLayout(layout);
}

void
TimerSlider::setMax( int max )
{
	if( max < 0 )
		max = 0;
	slider->setRange( 0, max );
}

int
TimerSlider::getValue() const
{
	return value;
}

/**
 * @brief Set the timer to assigned time.
 *
 * @param sec An integer represents time in seconds.
 * */
void
TimerSlider::setTimer( int sec )
{
	QString output;

	if( sec < 0 )
		return;
	sec_to_string(sec, output);
	timer->display(output);
	slider->setValue(sec);
	value = sec;
}

/**
 * @brief Prevent the sliding bar from being moved.
 *
 * Set the maximum value of sliding bar and timer to 0.
 */
void
TimerSlider::disableSlider()
{
	setMax(0);
	setTimer(0);
}

/* --- Utilities --- */
/**
 * @brief sec_to_string() is used to convert the time format to hh:mm:ss
 *
 * @param[in]  sec    Time to be converted(in second)
 * @param[out] output The output string
 */
void
sec_to_string( int sec, QString &output )
{
	if( sec < 0 )
		return;

	QString tmp_str;

	int hour, minute, second;
	hour = sec / (60*60);
	sec -= hour*(60*60);
	minute = sec / 60;
	second = sec % 60;

	tmp_str.setNum(hour);
	output += tmp_str;
	output += ":";

	tmp_str.setNum(minute);
	if( minute > 9 )
		output += tmp_str;
	else{
		output += "0";
		output += tmp_str;
	}
	output += ":";

	tmp_str.setNum(second);
	if( second > 9 ){
		output += tmp_str;
	}
	else{
		output += "0";
		output += tmp_str;
	}
}


